package com.nulp.psycho.db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.nulp.psycho.db.ConnectionManager;
import com.nulp.psycho.db.dao.BaseDao;
import com.nulp.psycho.db.mapping.Converter;
import com.nulp.psycho.db.model.GroupTest;

public class GroupTestDao implements BaseDao{
	
	private final String ADD_GROUP_TEST = "INSERT INTO group_test (group_id, test_id) VALUES (?,?)";
	private final String GET_GROUP_TEST_BY_ID = "SELECT * FROM group_test WHERE id = ?";
	private final String REMOVE_GROUP_TEST = "DELETE FROM group_test WHERE id = ?";
	private final String UPDATE_GROUP_TEST = "UPDATE group_test SET group_id=?, test_id=? WHERE id = ?";
	
	
	@Override
	public <T> void create(T element) {
		GroupTest temp = (GroupTest) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(ADD_GROUP_TEST)) {
			preparedStatement.setInt(1, temp.getGroupId());
			preparedStatement.setInt(2, temp.getTestId());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T read(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		GroupTest groupTest = null;
		try (PreparedStatement statement = connection
				.prepareStatement(GET_GROUP_TEST_BY_ID)) {
			statement.setInt(1, id);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				groupTest = Converter.<GroupTest> fromResaultSetToObject(rs,
						GroupTest.class);
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) groupTest;	
	}

	@Override
	public void delete(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(REMOVE_GROUP_TEST)) {
			preparedStatement.setInt(1, id);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@Override
	public <T> void update(T element) {
		GroupTest temp = (GroupTest) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(UPDATE_GROUP_TEST)) {
			preparedStatement.setInt(3, temp.getId());
			preparedStatement.setInt(1, temp.getGroupId());
			preparedStatement.setInt(2, temp.getTestId());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}
	
}
